<template>
  <view class="container">
    <view class="main-content">
      <!-- 数据输入区 -->
      <view class="input-sections">
        <!-- 原材料输入卡片 -->
        <view class="input-card">
          <view class="card-header">
            <text class="card-title">原材料</text>
            <view class="count-badge">
              <text class="card-count">已添加 {{ materials.length }} 根</text>
            </view>
          </view>
          <view class="input-container">
            <view class="input-section">
              <view class="input-box">
                <text class="input-box-label">长度(mm)</text>
                <uni-easyinput v-model="materialLength" type="number" placeholder="输入长度" class="custom-input"></uni-easyinput>
              </view>
              <view class="input-box">
                <text class="input-box-label">数量(根)</text>
                <uni-easyinput v-model="materialCount" type="number" placeholder="输入数量"
                  class="custom-input"></uni-easyinput>
              </view>
            </view>
            <button class="add-button" @tap="addMaterial">添加</button>
          </view>
          <scroll-view class="card-list" scroll-y>
            <view v-for="(item, index) in materials" :key="index" class="list-item">
              <view class="item-info">
                <uni-icons type="checkbox-filled" size="18" color="#4A90E2"></uni-icons>
                <text class="info-label">{{ item.length }}mm × {{ item.count }}根</text>
              </view>
              <view class="delete-btn" @tap="deleteMaterial(index)">
                <uni-icons type="trash-filled" size="18" color="#909399"></uni-icons>
              </view>
            </view>
          </scroll-view>
        </view>

        <!-- 零件输入卡片 -->
        <view class="input-card">
          <view class="card-header">
            <text class="card-title">零件需求</text>
            <view class="count-badge">
              <text class="card-count">已添加 {{ parts.length }} 件</text>
            </view>
          </view>
          <view class="input-container">
            <view class="input-section">
              <view class="input-box">
                <text class="input-box-label">标记</text>
                <uni-easyinput v-model="mark" type="text" placeholder="输入标记" class="custom-input"></uni-easyinput>
              </view>
              <view class="input-box">
                <text class="input-box-label">长度(mm)</text>
                <uni-easyinput v-model="partLength" type="number" placeholder="输入长度"
                  class="custom-input"></uni-easyinput>
              </view>
              <view class="input-box">
                <text class="input-box-label">数量(件)</text>
                <uni-easyinput v-model="partCount" type="number" placeholder="输入数量"
                  class="custom-input"></uni-easyinput>
              </view>
            </view>
            <button class="add-button parts-button" @tap="addPart">添加</button>
          </view>
          <scroll-view class="card-list" scroll-y>
            <view v-for="(item, index) in parts" :key="index" class="list-item">
              <view class="item-info">
                <uni-icons type="checkbox-filled" size="18" color="#4A90E2"></uni-icons>
                <text class="info-label">{{ item.length }}mm × {{ item.count }}件 {{ item.mark }}</text>
              </view>
              <view class="delete-btn" @tap="deletePart(index)">
                <uni-icons type="trash-filled" size="18" color="#909399"></uni-icons>
              </view>
            </view>
          </scroll-view>
        </view>

        <!-- 优化按钮 -->
		<view class="optimize-button-container">
			<button class="optimize-button" @tap="exportData">下载方案</button>
			<button class="optimize-button" @tap="startOptimize">开始优化</button>
		</view>
       
      </view>

      <!-- 结果展示区 -->
      <view class="result-card" v-if="results.material != null">
        <view class="result-header">
          <view class="result-title-section">
            <text class="card-title">优化方案</text>
            <view class="result-stats">
              <view class="stat-item">
                <uni-icons type="bars" size="20" color="#4A90E2"></uni-icons>
                <text class="stat-value">{{
                  results.material.map(i => i.count).reduce((a, b) => a + b)
                }}根</text>
              </view>
              <view class="stat-item">
                <uni-icons type="star-filled" size="20" color="#67C23A"></uni-icons>
                <text class="stat-value">{{ (results.fitness || 0).toFixed(2) }}%</text>
              </view>
            </view>
          </view>
          <view class="result-status">
            <uni-icons type="checkmarkempty" size="16" color="#67C23A"></uni-icons>
            <text class="status-text">{{ optimisationStatus }}</text>
          </view>
        </view>
        <view class="result-panel">
          <scroll-view class="result-list" scroll-y>
            <view v-for="(result, index) in results.material" :key="index" class="result-item">
              <view class="result-item-header">
                <view class="item-header-info">
                  <view class="material-info">
                    <text class="result-item-title">原料 {{ result.length }}mm x {{ result.count }}</text>
                    <text class="remain-info">余料：{{ result.remaining }}mm</text>
                    <view class="header-tags">
                      <text class="parts-tag">{{
                        result.parts.map(i => i.count).reduce((a, b) => a + b)
                      }}段</text>
                    </view>
                  </view>
                </view>
              </view>
              <view class="cutting-diagram">
                <view class="parts-grid">
                  <view v-for="(part, pIndex) in result.parts" :key="pIndex" class="part-item">
                    <view class="part-color-block" :style="{ backgroundColor: partColors[pIndex % partColors.length] }">
                      <text style="font-size: 8px;">{{ part.mark }}</text>
                    </view>
                    <text class="part-length">{{ part.length }}*{{ part.count }}</text>
                  </view>
                </view>
              </view>
            </view>
          </scroll-view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
const formatTime = require('@/utils/date.js').formatTime;
import {optimize,exportPfd} from "@/api/optimization.js"

export default {
  data() {
    return {
      materialLength: '',
      materialCount: '',
      materials: [
        { length: 6400, count: 99 },
        { length: 6000, count: 99 },
        { length: 5400, count: 99 }
      ],
      partLength: '',
      partCount: '',
      mark: 'A',
      parts: [],
      utilization: 100.0,
      optimisationStatus: '优化完成',
      partColors: ['#4A90E2', '#67C23A', '#E6A23C', '#F56C6C', '#909399'],
      results: {}
    };
  },
  methods: {
    addMaterial() {
      if (!this.materialLength || !this.materialCount) {
        uni.showToast({ title: '请输入完整信息', icon: 'none' });
        return;
      }
      for (let item of this.materials) {
        if (item.length == this.materialLength) {
          uni.showToast({ title: '不能输入重复的数据', icon: 'none' });
          return;
        }
      }
      this.materials.push({
        length: Number(this.materialLength),
        count: Number(this.materialCount)
      });
      this.materialLength = '';
      this.materialCount = '';
    },
    deleteMaterial(index) {
      this.materials.splice(index, 1);
    },
    addPart() {
      if (!this.partLength || !this.partCount) {
        uni.showToast({ title: '请输入完整信息', icon: 'none' });
        return;
      }
      for (let item of this.parts) {
        if (item.length == this.partLength) {
          uni.showToast({ title: '不能输入重复的数据', icon: 'none' });
          return;
        }
      }
      if (!this.mark) {
        uni.showToast({ title: '请输入标记', icon: 'none' });
        return;
      }
      for (let item of this.parts) {
        if (item.mark === this.mark) {
          uni.showToast({ title: '不能输入重复的标记', icon: 'none' });
          return;
        }
      }
      this.parts.push({
        length: Number(this.partLength),
        count: Number(this.partCount),
        mark: this.mark
      });
      this.partLength = '';
      this.partCount = '';
      let marks = this.parts.map(i => i.mark);
      let i = 65;
      while (marks.includes(String.fromCharCode(i))) {
        i++;
      }
      this.mark = String.fromCharCode(i);
    },
    deletePart(index) {
      this.parts.splice(index, 1);
    },
    startOptimize() {
      if (this.materials.length === 0 || this.parts.length === 0) {
        uni.showToast({ title: '请先添加原材料和零件', icon: 'none' });
        return;
      }
      uni.showLoading({ title: '优化计算中...' });
      this.startOptimisation();
    },
    async startOptimisation() {
      const startTime = new Date().getTime();

      try {
        uni.showLoading({ title: '优化中...' });

        const requestData = {
          materials: this.materials.map(item => ({
            length: item.length,
            count: item.count
          })),
          parts: this.parts.map(item => ({
            mark: item.mark,
            length: item.length,
            count: item.count
          }))
        };
		optimize(requestData).then(res=>{
			console.log(res);
			this.optimisationStatus = `优化完成 耗时：${new Date().getTime() - startTime}ms`;
			this.results = res;
			uni.showToast({ title: '优化完成', icon: 'success' });
		}).catch(res=>{
			 throw new Error(res.data?.message || '请求失败');
		})
      } catch (error) {
        console.error('优化失败:', error);
        this.optimisationStatus = '优化失败';
        this.results = {};
        uni.showToast({ title: error.message || '优化失败', icon: 'none' });
      } finally {
        uni.hideLoading();
      }
    },
	exportData() {
		exportPfd(this.results.id).then(ress=>{
			//保存到本地
			uni.saveFile({
			    tempFilePath: ress,
			    success: function(res) {
			        //res.savedFilePath文件的保存路径
			        //保存成功并打开文件
			        uni.openDocument({
			            filePath: res.savedFilePath,
			            success: (res) => console.log('成功打开文档')
			        })
			        console.log("bbb", res);
			    },
			    fail() {
			        console.log('打开失败')
			    }
			})
		})
	}
  },
  onShareTimeline() {
    return {
      title: '免费计算最优下料方案',
      path: '/pages/index/index',
      imageUrl: '/static/share.jpg',
      type: '0'
    };
  },
  onShareAppMessage() {
    return {
      title: '免费计算最优下料方案',
      path: '/pages/index/index',
      imageUrl: '/static/share.jpg',
      type: '0'
    };
  }
};
</script>

<style scoped>
	page {
		height: 100%;
	}

	.container {
		display: flex;
		flex-direction: column;
		height: 100%;
		background-color: #ffffff;
	}

	.page-header {
		padding: 40rpx 32rpx;
		background-color: #ffffff;
		border-bottom: 2rpx solid #f0f0f0;
		position: relative;
		z-index: 1;
		flex-shrink: 0;
	}

	.header-content {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.left-section {
		display: flex;
		flex-direction: column;
		gap: 8rpx;
	}

	.page-title {
		font-size: 24px;
		font-weight: 600;
		color: #1a1a1a;
		line-height: 1.2;
	}

	.sub-title {
		font-size: 14px;
		color: #666666;
	}

	.right-section {
		display: flex;
		align-items: center;
		justify-content: center;
		width: 80rpx;
		height: 80rpx;
		border-radius: 16rpx;
		background-color: #f0f5ff;
	}

	.main-content {
		flex: 1;
		padding: 24rpx;
		overflow: auto;
	}

	.input-sections {
		display: flex;
		flex-direction: column;
		gap: 24rpx;
		margin-bottom: 24rpx;
	}

	.input-card {
		background-color: #ffffff;
		border-radius: 16rpx;
		padding: 32rpx;
		border: 2rpx solid #f0f0f0;
	}

	.card-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 32rpx;
	}

	.card-title {
		font-size: 16px;
		font-weight: 500;
		color: #333333;
	}

	.count-badge {
		background: #F5F7FA;
		padding: 8rpx 16rpx;
		border-radius: 8rpx;
	}

	.card-count {
		font-size: 12px;
		color: #666666;
	}

	.parts-button {
		background: linear-gradient(135deg, #67C23A 0%, #529b2e 100%);
	}

	.card-subtitle {
		font-size: 14px;
		color: #666666;
		font-weight: 400;
	}

	.input-container {
		display: flex;
		flex-direction: column;
		gap: 32rpx;
	}

	.input-section {
		display: flex;
		gap: 32rpx;
	}

	.input-box {
		flex: 1;
		display: flex;
		flex-direction: column;
		gap: 16rpx;
	}

	.input-box-label {
		font-size: 14px;
		color: #333333;
		font-weight: 500;
		letter-spacing: 0.2px;
	}

	.custom-input {
		background-color: #FFFFFF;
		border-radius: 8rpx;
		border: 2rpx solid #E2E8F0;
		height: 88rpx;
	}

	.add-button {
		height: 72rpx;
		background: #4A90E2;
		color: #FFFFFF;
		font-size: 14px;
		font-weight: 500;
		border-radius: 8rpx;
		text-align: center;
		line-height: 72rpx;
		border: none;
	}

	.add-button:active {
		opacity: 0.9;
	}

	.card-list {
		max-height: 400rpx;
		padding: 8rpx 4rpx;
		margin: 0 -4rpx;
	}

	.list-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 24rpx;
		border-radius: 12rpx;
		background-color: #F8FAFC;
		margin-bottom: 16rpx;
		transition: all 0.3s ease;
	}

	.list-item:last-child {
		margin-bottom: 0;
	}

	.list-item:hover {
		background-color: #F5F7FA;
	}

	.item-info {
		display: flex;
		align-items: center;
		gap: 20rpx;
	}

	.info-label {
		font-size: 15px;
		color: #1F2937;
		font-weight: 500;
	}

	.delete-btn {
		width: 72rpx;
		height: 72rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		border-radius: 12rpx;
		transition: all 0.3s ease;
	}

	.delete-btn:active {
		background-color: #F0F2F5;
		transform: scale(0.95);
	}

	.result-card {
		grid-column: 1 / -1;
		background-color: #ffffff;
		border-radius: 16rpx;
		padding: 32rpx;
		border: 2rpx solid #f0f0f0;
	}

	.result-header {
		margin-bottom: 32rpx;
		padding-bottom: 24rpx;
		border-bottom: 2rpx solid #F0F2F5;
	}

	.result-title-section {
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-bottom: 16rpx;
	}

	.result-stats {
		display: flex;
		align-items: center;
		gap: 24rpx;
	}

	.stat-item {
		display: flex;
		align-items: center;
		gap: 8rpx;
		background-color: #F5F7FA;
		padding: 8rpx 16rpx;
		border-radius: 8rpx;
	}

	.stat-value {
		font-size: 14px;
		color: #1F2937;
		font-weight: 500;
	}

	.result-status {
		display: inline-flex;
		align-items: center;
		gap: 6rpx;
		background-color: #F0F9EB;
		padding: 6rpx 16rpx;
		border-radius: 32rpx;
	}

	.status-text {
		font-size: 12px;
		color: #67C23A;
	}

	.result-panel {
		display: flex;
		flex-direction: column;
		gap: 24rpx;
		white-space: nowrap;
	}

	.result-list {
		max-height: 960rpx;
		overflow: auto;
		padding: 8rpx;
		margin: -8rpx;
	}

	.result-item {
		background-color: #ffffff;
		border-radius: 12rpx;
		padding: 24rpx;
		margin-bottom: 16rpx;
		border: 2rpx solid #f0f0f0;
	}

	.result-item:last-child {
		margin-bottom: 0;
	}

	.result-item-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 24rpx;
	}

	.item-header-info {
		display: flex;
		flex-direction: column;
		gap: 12rpx;
	}

	.material-info {
		display: flex;
		align-items: center;
		gap: 24rpx;
	}

	.remain-info {
		font-size: 14px;
		color: #F56C6C;
	}

	.result-item-title {
		font-size: 16px;
		color: #333333;
		font-weight: 500;
	}

	.header-tags {
		display: flex;
		gap: 12rpx;
	}

	.length-tag,
	.parts-tag {
		font-size: 12px;
		padding: 4rpx 12rpx;
		border-radius: 4rpx;
	}

	.length-tag {
		background-color: #F2F6FC;
		color: #4A90E2;
	}

	.parts-tag {
		background-color: #F0F9EB;
		color: #67C23A;
	}

	.cutting-diagram {
		background-color: #F5F7FA;
		border-radius: 8rpx;
		padding: 24rpx;
		margin-bottom: 16rpx;
	}

	.parts-grid {
		display: grid;
		grid-template-columns: repeat(auto-fill, minmax(160rpx, 1fr));
		gap: 16rpx;
	}

	.part-item {
		display: flex;
		align-items: center;
		gap: 12rpx;
		background-color: #FFFFFF;
		padding: 16rpx;
		border-radius: 8rpx;
		border: 2rpx solid #f0f0f0;
	}

	.part-color-block {
		padding-left: 3px;
		padding-right: 3px;
		min-width: 24rpx;
		height: 24rpx;
		border-radius: 6rpx;
		flex-shrink: 0;
		display: flex;
		align-items: center;
		justify-content: center;
		color: #FFFFFF;
	}

	.part-length {
		font-size: 14px;
		color: #333333;
		font-weight: 500;
	}

	.cutting-info {
		display: flex;
		align-items: center;
		gap: 8rpx;
	}

	.remain-text {
		font-size: 12px;
		color: #909399;
	}

	.remain-value {
		font-size: 12px;
		color: #F56C6C;
		font-weight: 500;
	}
	.optimize-button-container {
	  display: flex;   
	}
	.optimize-button {
		flex: 1;
		margin: 32rpx 24rpx;
		height: 88rpx;
		background: linear-gradient(135deg, #4A90E2 0%, #357ABD 100%);
		color: #FFFFFF;
		font-size: 16px;
		font-weight: 500;
		border-radius: 12rpx;
		text-align: center;
		line-height: 88rpx;
		border: none;
		box-shadow: 0 4rpx 12rpx rgba(74, 144, 226, 0.2);
	}

	.optimize-button:active {
		transform: scale(0.98);
		box-shadow: 0 2rpx 8rpx rgba(74, 144, 226, 0.1);
	}

	/deep/ ::-webkit-scrollbar {
		width: 4rpx;
		background: transparent;
	}

	/deep/ ::-webkit-scrollbar-thumb {
		background-color: rgba(0, 0, 0, 0.1);
		border-radius: 2rpx;
	}
</style>